package com.yimi.yinhepda.views.main.home_module;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.pda.uce.commom.util.AppUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.uce.pda.module.ConnectionResultLister;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.base.BaseFragment;
import com.yimi.yinhepda.db.dao.FuncBtnTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.FuncBtnTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.event.CreateStowagesEvent;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.OnRecyclerItemClickListener;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.views.load_module.CreateLoadTaskActivity;
import com.yimi.yinhepda.views.load_module.LoadTaskActivity;
import com.yimi.yinhepda.views.load_module.NewLoadTaskActivity;
import com.yimi.yinhepda.views.load_module.SetOutSealCarActivity;
import com.yimi.yinhepda.views.main.home_module.presenter.LoadTaskPresenter;
import com.yimi.yinhepda.views.unload_module.TaskCashCollectionActivity;
import com.yimi.yinhepda.views.unload_module.UnBlocking.BlockingUnloadTaskActivity;
import com.yimi.yinhepda.views.unload_module.UnBlocking.UnBlockingActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author: lj
 * Date: 2019/9/19 15:52
 * Description:首页
 */
public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private ItemTouchHelper itemTouchHelper;
    private List<FuncBtnTable> funcBtnTableList=new ArrayList<>();
    LoadTaskPresenter loadTaskPresenter;

    BaseQuickAdapter<FuncBtnTable, BaseViewHolder> adapter;
    SwipeRefreshLayout swipe;

    List<UnloadTaskTable> listUnloadTaskTable;

    UnloadTaskTableDao mUnloadTaskTableDao = new UnloadTaskTableDao();
    @Override
    public String getPageName() {
        return "首页";
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_home_new;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadTaskPresenter = new LoadTaskPresenter();
        mUnloadTaskTableDao = new UnloadTaskTableDao();
        initView();
        EventBus.getDefault().register(this);
        requestTask();
    }

    public boolean showDeleteBtn;
    private void initView() {
        swipe=getView().findViewById(R.id.swipe);
        swipe.setProgressViewOffset(false, (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, getResources().getDisplayMetrics()), (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60f,getResources().getDisplayMetrics()));
        swipe.setOnRefreshListener(this);
        RecyclerView recyclerView = getView().findViewById(R.id.grid_view_common);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        adapter = new BaseQuickAdapter<FuncBtnTable, BaseViewHolder>(R.layout.adapter_comm_func_item, funcBtnTableList) {
            @Override
            protected void convert(BaseViewHolder holder, final FuncBtnTable data, int postion) {
                holder.setText(R.id.tv_func_name, data.getName());
                holder.setImageResource(R.id.iv_func_pic, data.getPicId());

                if (showDeleteBtn && !data.getNameCode().equals(Common.FUNC_ADD)) {
                    holder.getView(R.id.iv_delete_btn).setVisibility(View.VISIBLE);
                    Animation shake;
                    if (postion % 2 == 1) {
                        shake = AnimationUtils.loadAnimation(mContext, R.anim.anim_func);
                    } else {
                        shake = AnimationUtils.loadAnimation(mContext, R.anim.anim_func2);
                    }
                    shake.reset();
                    shake.setFillAfter(true);
                    holder.itemView.startAnimation(shake);
                } else if (!showDeleteBtn && data.getNameCode().equals(Common.FUNC_ADD)) {
                    holder.itemView.setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.iv_delete_btn).setVisibility(View.GONE);
                    holder.itemView.setVisibility(View.VISIBLE);
                }
                int deptType = SharedPreferUtil.getInstance().getIntValue(Common.DEPT_TYPE);
                if (deptType == 5 || deptType == 6) {
                    if (data.getNameCode().equals(Common.FUNC_QDGL) || data.getNameCode().equals(Common.FUNC_LHSM)) {
                        //分拨屏蔽签到管理、揽货扫描
                        holder.itemView.setEnabled(false);
                    } else {
                        holder.itemView.setEnabled(true);
                    }
                } else {
                    if (data.getNameCode().equals(Common.FUNC_FBZT) || data.getNameCode().equals(Common.FUNC_KYDH)) {
                        //网点屏蔽分拨自提、同行卸车
                        holder.itemView.setEnabled(false);
                    } else {
                        holder.itemView.setEnabled(true);
                    }
                }
            }
        };
        recyclerView.setAdapter(adapter);


        recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView) {
            @Override
            public void onLongClick(RecyclerView.ViewHolder vh) {
                if (!showDeleteBtn) {
                    showDeleteBtn = true;
                    adapter.notifyDataSetChanged();
                    SoundVibratorManager.playVibrator(getContext(), 70);
                } else {
                    FuncBtnTable funcBtnTable = funcBtnTableList.get(vh.getLayoutPosition());
                    if (!funcBtnTable.getNameCode().equals(Common.FUNC_ADD)) {
                        try{
                            if (vh!=null){
                                itemTouchHelper.startDrag(vh);
                            }
                            SoundVibratorManager.playVibrator(getContext(), 70);
                        }catch (Exception e){

                        }

                    }
                }
            }

            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                final FuncBtnTable funcBtnTable = funcBtnTableList.get(vh.getLayoutPosition());
                if (adapter != null && showDeleteBtn && !funcBtnTable.getNameCode().equals(Common.FUNC_ADD)) {
                    //点击删除
                    MyDialog dialog = new MyDialog(getContext());
                    dialog.setIcon(R.drawable.alert);
                    dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                    dialog.setTitle("提示");
                    dialog.setMessage("确定删除" + funcBtnTable.getName() + "？");
                    dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            funcBtnTableList.remove(funcBtnTable);
                            //设置功能背景图片
                            Common.setFuncPic(funcBtnTableList, false);
                            adapter.notifyDataSetChanged();
                            //修改常用功能数据表
                            funcBtnTable.setIsCommUse(0);
                            try {
                                new FuncBtnTableDao().update(funcBtnTable);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                            EventBus.getDefault().post("");
                        }
                    });
                    dialog.setNegativeClickListener(0, "取消", null);
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setCancelable(false);
                    dialog.show();
                }
                else{
                    //点击跳转
                    if (!vh.itemView.isEnabled()) {
                        return;
                    }
                    goToActivity(funcBtnTable);
                }

            }
        });


        Button btnAddIcon = getView().findViewById(R.id.btn_add);
        btnAddIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FunctionBtnEditActivity.class);
                startActivity(intent);
            }
        });

    }

    private void initData(){
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                //查询暂存的配置单号
                listUnloadTaskTable = mUnloadTaskTableDao.findUnComplete(0, sharedPreferUtil.getValue(Common.USER_CODE));
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onCompleted() {
                loadTaskPresenter.initView(getView(), getActivity());
                loadTaskPresenter.getCreatedTask(1,listUnloadTaskTable,null);
                loadTaskPresenter.getCreatedTask(2,listUnloadTaskTable,null);
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }


    /**
     * 界面获取焦点
     */
    @SuppressWarnings("ConstantConditions")
    private void getFocus() {
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    if (adapter != null && showDeleteBtn) {
                        showDeleteBtn=false;
                        adapter.notifyDataSetChanged();
                        return true;
                    }
                }
                return false;
            }
        });
    }



    @Override
    public void onResume() {
        super.onResume();
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                if (funcBtnTableList == null) {
                    funcBtnTableList = new ArrayList<>();
                }
                funcBtnTableList.clear();
                funcBtnTableList.addAll(new FuncBtnTableDao().findByCommId(1));
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                //设置功能背景图片
                Common.setFuncPic(funcBtnTableList, false);
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                getFocus();
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });

    }


    private void requestTask(){
        loadTaskPresenter.clearData();
        initData();
    }


    // 在主线程更新UI
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(CreateStowagesEvent event) {
        if (event.getFromActivity()==3||event.getFromActivity()==4){
            if (loadTaskPresenter!=null){
                loadTaskPresenter.removeTask(event.getTaskNos());
            }
        }
        else if(event.getFromActivity()==1||event.getFromActivity()==2){
             onRefresh();
        }

    }


//
//
//    R.id.ll_seal_car_list_new,
//    R.id.ll_daoche_unSeal, R.id.ll_unload_task, R.id.ll_unload_temp_save,
//    R.id.ll_create_check, R.id.ll_check_balance, R.id.ll_forklift_sort, R.id.ll_dispatch_task, R.id.ll_edit,
//    R.id.ll_daoche_unSeal_new, R.id.ll_unload_task_new

    @OnClick({R.id.relative_load_task, R.id.relative_close_car, R.id.relative_de_archive_task, R.id.relative_unload_task
             ,R.id.ll_task_list,R.id.ll_seal_car_list,R.id.ll_seal_car_list_new,R.id.ll_daoche_unSeal_new,R.id.ll_unload_task_new,R.id.ll_unload_temp_save})
    @Override
    protected void onClickBtn(View v) {
        super.onClickBtn(v);
        switch (v.getId()) {
            case R.id.relative_load_task:
                //融合装车任务
                toActivity(NewLoadTaskActivity.class);
                break;
            case R.id.relative_close_car:
                //创建装车任务
                toActivity(CreateLoadTaskActivity.class);
                break;
            case R.id.ll_task_list:
                //任务列表
                if (sharedPreferUtil.getOfflineMode()) {
                    ToastUtil.showToast(getString(R.string.no_use_in_offline));
                    return;
                }
                toActivity(LoadTaskActivity.class);
                break;
            case R.id.ll_seal_car_list:
                //封车列表
                toActivity(SetOutSealCarActivity.class);
                break;
            case R.id.relative_de_archive_task:
                //到车解封
                toActivity(UnBlockingActivity.class);
                break;
            case R.id.relative_unload_task:
                //卸车任务
                toActivity(BlockingUnloadTaskActivity.class);
                break;
            case R.id.ll_unload_temp_save:
                //卸车暂存
                toActivity(TaskCashCollectionActivity.class);
                break;
//            case R.id.ll_create_check:
//                //创建盘点单
//                toActivity(CheckTaskCreateActivity.class);
//                break;
//            case R.id.ll_check_balance:
//                //复称检查
//                if (sharedPreferUtil.getOfflineMode()) {
//                    ToastUtil.showToast(getString(R.string.no_use_in_offline));
//                    return;
//                }
//                //复秤检查
//                Intent intent = new Intent(getContext(), CheckBalanceActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("iService", MainActivity.iService);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                break;
//            case R.id.ll_forklift_sort:
//                //叉车分拣
//                toActivity(ForkliftUnBindActivity.class);
//                break;
//            case R.id.ll_dispatch_task:
//                //配送任务
//                toActivity(DispatchTaskActivity.class);
//                break;
//            case R.id.ll_edit:
//                //编辑
//                toActivity(FunctionBtnEditActivity.class);
//                break;
            case R.id.ll_seal_car_list_new:
                //融合封车管理
                toActivity(SetOutSealCarActivity.class);
                break;
            case R.id.ll_daoche_unSeal_new:
                //融合到车解封
                toActivity(UnBlockingActivity.class);
                break;
            case R.id.ll_unload_task_new:
                //融合卸车任务
                toActivity(BlockingUnloadTaskActivity.class);
                break;
            default:
                break;
        }
    }




    @Override
    public void onRefresh() {
        long requestTime=sharedPreferUtil.getLongValue("requestTime");
        if(AppUtil.isPassTimeTwentySecond(requestTime)){
            sharedPreferUtil.setLongValue("requestTime",System.currentTimeMillis());
            swipe.setRefreshing(true);
            loadTaskPresenter.clearData();
            loadTaskPresenter.getCreatedTask(1,listUnloadTaskTable,null);
            loadTaskPresenter.getCreatedTask(2, listUnloadTaskTable, new ConnectionResultLister() {
                @Override
                public void getResult(int errorCode, Object o) {
                    swipe.setRefreshing(false);
                }
            });
        }
        else{
            ToastUtil.showToast(getString(R.string.refresh_is_more));
            swipe.setRefreshing(false);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
